#include "test_ota.h"
#include "cm_uart.h"
#include "cm_demo_uart.h"
#include "cm_ftp.h"
#include "cm_mem.h"


#define TEST_DEMO_OTA_BIN_FILE       "SZXWDC.bin"          //ftp服务器上的升级包
#define TEST_MAX_DIFF_SIZE           (500 * 1024)            //存放升级包的缓存区大小

#define TEST_OTA_FTP_ADDRESS         "39.106.55.121"         //ftp服务器地址，用户写入
#define TEST_OTA_FTP_PORT            (21)                    //ftp服务器端口，用户写入
#define TEST_OTA_FTP_USER            "asdasd"                  //ftp登录名，用户写入
#define TEST_OTA_FTP_PASSWD          "asdasd"                 //ftp登录密码，用户写入

static char *ota_diff_buf = NULL;          //升级包缓存
static int test_get_len = 0;
static int total_len = 0;
static int ftp_size = 0;


static void test_firmware_download()
{
    int count = 0;
	int32_t handle;
    cm_ftp_config_t config= {0};
    
    //cm_demo_printf("ota init ret:%d\n", cm_ota_init());
    ota_diff_buf = cm_malloc(TEST_MAX_DIFF_SIZE);
    if(NULL == ota_diff_buf)
    {
        cm_demo_printf("cm_malloc fail!\n");
        return;
    }
    memset(ota_diff_buf, 0, TEST_MAX_DIFF_SIZE);
    total_len = 0;
    
    cm_demo_printf("[FTP]test start\n");
    
	config.url = TEST_OTA_FTP_ADDRESS;
	config.port = TEST_OTA_FTP_PORT;
	config.username = TEST_OTA_FTP_USER;
	config.passwd = TEST_OTA_FTP_PASSWD;
	config.trans_mode = 1;
	config.data_type = 0;
	config.rsptimeout = 10000;
    config.cid = 1;
    config.ssl_id = 0;
    config.ssl_mode = 0;
	handle = cm_ftp_open(&config);
	cm_demo_printf("[FTP]Ftp open:%d\n", handle);
	ftp_size = cm_ftp_get_file_size(handle,TEST_DEMO_OTA_BIN_FILE);
	if(handle < 0)
	{
		cm_demo_printf("[FTP] open failed\n");
		return;
	}
    for(int i = 0;i < ftp_size;)
    {
        total_len += cm_ftp_get_file(handle,0,TEST_DEMO_OTA_BIN_FILE,i, &ota_diff_buf[i],10000);
        i += 10000;
        cm_demo_printf("total len:%d\n",total_len);
    }
    
    cm_demo_printf("total_len %d\r\n", total_len);
    cm_ftp_close(handle);
}

static void test_firmware_write()
{
    int ret = -1;
    cm_demo_printf("total_len %d\r\n", total_len);
    
    for (int i = 0; i < total_len; i+= 512)
    {
        if ((i + 512) > total_len)
        {
            ret = cm_ota_firmware_write(&ota_diff_buf[i], (total_len - i));
            cm_demo_printf("ota cm_ota_firmware_write ret:%d\n",ret);
        }
        else
        {
            ret = cm_ota_firmware_write(&ota_diff_buf[i], 512);
        }
    }
}

void test_fota_result_callback(cm_fota_error_e error)
{
    switch(error)
    {
        case CM_FOTA_CMIOT_ERROR_UNKNOW:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_UNKNOW\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_CONFIG_FILE:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_CONFIG_FILE\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_URL_TYPE:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_URL_TYPE\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_WRITE_CONFIG:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_WRITE_CONFIG\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_UPDATE:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_UPDATE\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_DOWNLOAD:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_DOWNLOAD\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_DOWNLOAD_MAX_RETRY:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_DOWNLOAD_MAX_RETRY\n");
            break;
        }
        case CM_FOTA_CMIOT_ERROR_NO_NETWORK:
        {
            cm_demo_printf("CM_FOTA_CMIOT_ERROR_NO_NETWORK\n");
            break;
        }
        // case CM_FOTA_CMIOT_ERROR_PKG_TYPE_FILESYSTEM:
        // {
        //     cm_demo_printf("CM_FOTA_CMIOT_ERROR_PKG_TYPE_FILESYSTEM\n");
        //     break;
        // }
        // case CM_FOTA_CMIOT_ERROR_PKG_TYPE_MINI:
        // {
        //     cm_demo_printf("CM_FOTA_CMIOT_ERROR_PKG_TYPE_MINI\n");
        //     break;
        // }
        default :
        {
            cm_demo_printf("error,no error state exist\n");
            break; 
        }
    }   
}

void cm_test_ota_operation(unsigned char *cmd[],int len)
{
    unsigned char operation[20] = {0};
    sprintf(operation, "%s", cmd[2]);
    /*FOTA API*/
    if(0 == strcmp(operation, "FOTA_SET_URL"))
    {
        uint8_t url[1000] = {0};
        for(int i = 3;i<len;++i)
        {
            strncat(url,cmd[i],strlen(cmd[i]));
            if(i != (len - 1))
            {
                strncat(url,":",1);
            }
        }
        //cm_demo_printf("cm_fota_set_url ret:%d\n",cm_fota_set_url("http://39.106.55.121:8080/download/system_patch.bin_1"));
        int set_url = cm_fota_set_url(url);
        cm_demo_printf("cm_fota_set_url ret:%d\n",set_url);
        OCTEST_FUNC_EXPECT_EQUAL_INT32(0,set_url,cm_fota_set_url);
    }
    else if (0 == strcmp(operation, "SET_AUTH"))
    {
        char *username = cmd[3];
        char *passwd =cmd[4];
        int set_auth = cm_fota_set_auth(username,passwd);
        cm_demo_printf("cm_fota_set_auth ret:%d\n",set_auth);
        OCTEST_FUNC_EXPECT_EQUAL_INT32(0,set_auth,cm_fota_set_auth);
    }
    else if (0 == strcmp(operation, "FOTA_SET_REBOOT_TIME"))
    {
        cm_fota_reboot_time time = {
            .first_timeout = atoi(cmd[3]),                  /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第一次尝试重启的超时时间 */
            .second_timeout = atoi(cmd[4]),                 /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第二次尝试重启的超时时间 */
            .third_timeout = atoi(cmd[5]),                  /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第三次尝试重启的超时时间 */
            .fourth_timeout = atoi(cmd[6]),                 /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第四次尝试重启的超时时间 */
            .fifth_timeout = atoi(cmd[7]),                  /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第五次尝试重启的超时时间 */
            .sixth_timeout = atoi(cmd[8]),                  /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第六次尝试重启的超时时间 */
            .constant_timeout = atoi(cmd[9])                /*!< 单位：分钟；范围：3分钟至3天（3~3*24*60）；含义：一次升级期间任一阶段升级失败或超时未完成时，第七次及之后的尝试重启的超时时间 */
        };
        int reboot_time = cm_fota_set_reboot_time(&time);
        cm_demo_printf("cm_fota_set_reboot_time ret:%d\n",reboot_time);
        OCTEST_FUNC_EXPECT_EQUAL_INT32(0,reboot_time,cm_fota_set_reboot_time);
    }
    else if (0 == strcmp(operation, "FOTA_READ_CFG"))
    {
        cm_fota_info_t cfg = {0};
        cm_demo_printf("cm_fota_read_config no ret\n");
        cm_fota_read_config(&cfg);
        cm_demo_printf("cfg stage:%d\n",cfg.fixed_info.stage);               /*!< FOTA升级进行状态 */
        cm_demo_printf("cfg fota_mode:%d\n",cfg.fixed_info.fota_mode);        /*!< fota升级模式, 0: HTTP/HTTPS */
        cm_demo_printf("cfg url:%s\n",cfg.fixed_info.url);   /*!< 服务器url */
        cm_demo_printf("cfg username:%s\n",cfg.fixed_info.username);   /*!< 用户名*/
        cm_demo_printf("cfg passwd:%s\n",cfg.fixed_info.passwd);     /*!< 密码 */
        cm_demo_printf("cfg isSetTimeout:%d\n",cfg.extend_info.isSetTimeout);                    /*!< 用户是否设置重启时间。非0：用户已成功设置；0：用户未设置或设置不合法，采用默认参数 */
        cm_demo_printf("cfg failurefailure:%d\n",cfg.extend_info.failure);                         /*!< 失败次数 */
        cm_demo_printf("cfg first_timeout:%d\n",cfg.extend_info.timeout.first_timeout);         /*!< 用户配置时间参数 */
        cm_demo_printf("cfg second_timeout:%d\n",cfg.extend_info.timeout.second_timeout); 
        cm_demo_printf("cfg third_timeout:%d\n",cfg.extend_info.timeout.third_timeout); 
        cm_demo_printf("cfg fourth_timeout:%d\n",cfg.extend_info.timeout.fourth_timeout); 
        cm_demo_printf("cfg fifth_timeout:%d\n",cfg.extend_info.timeout.fifth_timeout); 
        cm_demo_printf("cfg sixth_timeout:%d\n",cfg.extend_info.timeout.sixth_timeout); 
        cm_demo_printf("cfg constant_timeout:%d\n",cfg.extend_info.timeout.constant_timeout);     
    }
    else if (0 == strcmp(operation, "SET_GET_OTA_PLAN"))
    {
        cm_fota_asr_plan_e plan = cm_fota_get_ota_plan();
        cm_demo_printf("default plan:%d\n",plan);
        OCTEST_FUNC_EXPECT_EQUAL_INT32(CM_FOTA_ASR_PLAN_MINI_INTEGRATE,plan,cm_fota_get_ota_plan);
        if(0 == strcmp(cmd[3],"MINI_INTEGRATE"))
        {
            cm_fota_result_callback cb = test_fota_result_callback;
            cm_fota_res_callback_register(cb);
            plan = CM_FOTA_ASR_PLAN_MINI_INTEGRATE;
            cm_fota_set_ota_plan(plan);
            plan = cm_fota_get_ota_plan();
            cm_demo_printf("set then get plan:%d\n",plan);
            OCTEST_FUNC_EXPECT_EQUAL_INT32(CM_FOTA_ASR_PLAN_MINI_INTEGRATE,plan,cm_fota_get_ota_plan);
        }
        else if(0 == strcmp(cmd[3],"MINI"))
        {
            plan = CM_FOTA_ASR_PLAN_MINI;
            cm_fota_set_ota_plan(plan);
            plan = cm_fota_get_ota_plan();
            cm_demo_printf("set then get plan:%d\n",plan);
            OCTEST_FUNC_EXPECT_EQUAL_INT32(CM_FOTA_ASR_PLAN_MINI,plan,cm_fota_get_ota_plan);
        }
        else{
            cm_demo_printf("param error!\n");
            return;
        }
    }
    else if (0 == strcmp(operation, "FOTA_REG_FOTA_CB"))
    {
        cm_fota_result_callback cb = test_fota_result_callback;
        cm_fota_res_callback_register(cb);

    }
    else if (0 == strcmp(operation, "FOTA_UPGRADE"))
    {
        int exec_uograde = cm_fota_exec_upgrade();
        cm_demo_printf("cm_fota_exec_upgrade ret:%d\n",exec_uograde);
         OCTEST_FUNC_EXPECT_EQUAL_INT32(0,exec_uograde,cm_fota_exec_upgrade);
    }
    /*normal ota api*/
    // else if(0 == strcmp(operation, "OTA_CAPACITY"))
    // {
    //     cm_demo_printf("cm_ota_get_capacity() %d\r\n", cm_ota_get_capacity());
    // }
    // else if (0 == strcmp(operation, "OTA_INIT"))
    // {
    //     cm_demo_printf("cm_ota_init ret: %d\n", cm_ota_init());
    // }
    // else if (0 == strcmp(operation, "OTA_DOWNLOAD"))
    // {
    //     cm_demo_printf("[OTA] firmware download\n");
    //     test_firmware_download();
    // }
    // else if (0 == strcmp(operation, "OTA_SET_SIZE"))
    // {
    //     int size = atoi(cmd[3]);
    //     cm_ota_set_otasize(size);
    // }
    // else if (0 == strcmp(operation, "OTA_WRITE"))
    // {
    //     cm_demo_printf("[OTA] firmware write\n");
    //     test_firmware_write();
    //     //cm_free(ota_diff_buf);
    //     //ota_diff_buf = NULL;
    // }
    // else if (0 == strcmp(operation, "OTA_GET_SIZE"))
    // {
    //     cm_demo_printf("[OTA] firmware file size is %d\n", cm_ota_get_written_size());
    // }
    // else if (0 == strcmp(operation, "OTA_ERASE"))
    // {
    //     cm_demo_printf("[OTA] firmware file ERASE: %d\n", cm_ota_firmware_erase());
    // }
    // else if (0 == strcmp(operation, "OTA_UPGRADE"))
    // {
    //     cm_demo_printf("[OTA] firmware upgrade: %d\n", cm_ota_upgrade());
    // }
    // else if(0 == strcmp(operation, "VERSION"))
    // {
    //     cm_demo_printf("ota version 1.0\n");
    // }
    // else
    // {
    //     cm_demo_printf("[OTA] Illegal operation\n"); 
    // }
}
